package com.oracle.sbdb.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

public class JSONUtility {
	public static String bean2Json(Object obj){
		String res = null;
		try{
			JSONObject jsonObject=JSONObject.fromObject(obj);
			if(jsonObject != null){
				res = jsonObject.toString();
			}
		}catch (Exception e){
			e.printStackTrace();
		}
        return res;
    }
    @SuppressWarnings("unchecked")
    public static <T> T json2Bean(String jsonStr,Class<T> objClass){
    	T res = null;
    	try{
    		JSONObject jsonObject = JSONObject.fromObject(jsonStr);
    		if(jsonObject != null){
    			res = (T) JSONObject.toBean(jsonObject, objClass);
    		}
    	}catch(Exception e){
    		e.printStackTrace();
    	}
        return res;
    }
    
    public static JSONObject getRequestString(HttpServletRequest request){
    	JSONObject res = null;
    	try{
	        BufferedReader br = new BufferedReader(new InputStreamReader(  
	                (ServletInputStream) request.getInputStream(), "UTF-8"));  
	        StringBuffer sb = new StringBuffer("");  
	        String temp = null;  
	        while ((temp = br.readLine()) != null) {  
	            sb.append(temp);  
	        }  
	        br.close();  
	        res = JSONObject.fromObject(sb.toString()); 
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	return res;
    }
}
